#!/bin/bash

_script_name="setvars.sh"

unset hmpi_vars
unset kupl_vars

show_help() {
    echo "Usage: source ${_script_name}" '[--force] [--kml_$k=$v] [--kupl_mode=$v] [--use-bisheng] [--help]'
    echo "  --force        Force ${_script_name} to run again, overload environment variables."
    echo '  --kml_$k=$v    The parameter is used to set environment variables related to KML sub-libraries.'
    echo "                 The following parameters can be configured:"
    echo "                     --kml_kblas=[multi(default)|locking|nolocking],"
    echo "                     --kml_kspblas=[multi(default)|single],"
    echo "                     --kml_kvml=[single(default)|multi]."
    echo '  --kupl_mode=$v The parameter is used to set environment variables related to KUPL sub-libraries.'
    echo "                 The following parameters can be configured:"
    echo "                     --kupl_mode=[release(default)|prof]."
    echo "                 When you execute the 'source setvars.sh' command, the values of the parameters mentioned above"
    echo "                 will be reset to their default values. If you want the parameters to retain their original"
    echo "                 non-default values, please explicitly append the original non-default values for these parameters."
    echo '  --hmpi_mode=$v The parameter is used to set environment variables related to HMPI sub-libraries.'
    echo "                 The following parameters can be configured:"
    echo "                     --hmpi_mode=[release(default)|debug]."
    echo "                 When you execute the 'source setvars.sh' command, the values of the parameters mentioned above"
    echo "                 will be reset to their default values. If you want the parameters to retain their original"
    echo "                 non-default values, please explicitly append the original non-default values for these parameters."
    echo "  --use-bisheng  If this parameter is added, the command is used to configure environment variables for"
    echo "                 Bisheng compiler and components built by Bisheng compiler. Otherwise, this command is used to"
    echo "                 configure the environment variables of the GCC compiler and components built by GCC compiler."
    echo "  --reset        The parameter is used to clear the environment variables set by this script."
    echo "  --help         Display this help message and exit."
}


if [ "$0" = "$BASH_SOURCE" ]; then
    echo "Incorrect usage: ${_script_name} must be sourced."
    echo ""
    show_help
    exit
fi

_script_dir=$(cd $(dirname $BASH_SOURCE) && command pwd -P)

process_comp_name() {
    local name="$1"
    name=`echo $name | tr '[:upper:]' '[:lower:]'` # to lower case
    echo $name
}

reset_vars() {
    if [ "$HPCKIT_SETVARS" != "1" ] ; then
        return
    fi
    local envs=$(env | grep $_script_dir)
    for line in ${envs[@]} ; do
        local env_key=${line%=*}
        local env_value=${line#*=}
        env_value=$(echo "$env_value" | tr ':' '\n' | grep -v "$_script_dir" | paste -sd ':' )
        eval "${env_key}=\"${env_value}\""
    done
    unset HPCKIT_SETVARS
}

help=0
force=0
use_bisheng=0
compiler="gcc"
kml_vars=""
args_comps=()

# parse args
while [ "$#" -gt 0 ]; do
    case "$1" in
    --help)
        help=1
        break
        ;;
    --force)
        force=1
        shift
        ;;
    --use-bisheng)
        use_bisheng=1
        compiler="bisheng"
        shift
        ;;
    --reset)
        reset_vars
        return
        ;;
    --*_*=*)
        comp=`echo $1 | awk -F'--|_' '{print $2}'`
        comp=`process_comp_name $comp` # to lower case
        kv="${1#*_}"
        key=${kv%%=*}
        value=${kv#*=}
        # kv pair append to ${comp}_vars
        eval "${comp}_vars+=\" --$key=$value\""
        args_comps+=("$comp")
        # echo comp: $comp, key: $key, value: $value
        shift
        ;;
    *)
        echo "Unknown option: $1"
        echo ""
        show_help
        return
        shift
        ;;
    esac
done

# Remove Duplicates of components get from args
args_comps=($(printf '%s\n' "${args_comps[@]}"|sort -u))

# show help
if [ $help -ne 0 ] ; then
    show_help
    return
fi

# force execution
if [ "$HPCKIT_SETVARS" == "1" ] ; then
    if [ $force -eq 0 ] ; then
        echo "Warning: ${_script_name} has already been executed."
        echo "Use the '--force' option to force a re-execution."
        echo ""
        show_help
        return
    fi
fi


echo "* HPCKit setting environment variables..."
echo ""

# find all script
comp_name_array=()
find_all_comp() {
    declare -A comp_names
    comp_script_array=($(command ls "$_script_dir"/*/*/env/$_script_name 2>/dev/null | awk 'NF'))
    # get component names from directory structure
    for comp_script in ${comp_script_array[@]} ; do
        comp_name=$(basename -- "$(dirname -- "$(dirname -- "$(dirname -- "$comp_script")")")")
        comp_name=`process_comp_name $comp_name`
        if [[ ! "${comp_names[$comp_name]}" ]]; then
            comp_name_array+=("$comp_name")
            comp_names["$comp_name"]=1
        fi
    done
    comp_script_array_ext=($(command ls "$_script_dir"/*/env/$_script_name 2>/dev/null | awk 'NF'))
    for comp_script in ${comp_script_array_ext[@]} ; do
        comp_name=$(basename -- "$(dirname -- "$(dirname -- "$comp_script")")")
        comp_name=`process_comp_name $comp_name`
        if [[ ! "${comp_names[$comp_name]}" ]]; then
            comp_name_array+=("$comp_name")
            comp_names["$comp_name"]=1
        fi
    done
}
find_all_comp
for i in ${!comp_name_array[@]}; do
    comp=${comp_name_array[i]}
    if [ "${comp}" = "hio" ]; then
        script=$_script_dir/$comp/env/$_script_name
    else
        script=$_script_dir/$comp/$compiler/env/$_script_name
    fi
    # ${comp}_vars are set by args parsing
    if [ -r $script ]; then
        vars_name="${comp}_vars"
        vars=${!vars_name}
        echo "* $comp setvars"
        source $script $vars
    fi
done

echo ""
echo "* HPCKit environment variables inited"

# clean ${comp}_vars
for comps in $args_comps ; do
    eval "${comp}_vars=\"\""
done

export HPCKIT_SETVARS=1